package com.xiaozhi.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.time.Duration;
import java.util.Map;
import java.util.HashMap;

/**
 * DeepSeek AI服务健康检查组件
 * 用于监控DeepSeek API的可用性和响应时间
 */
@Component
public class DeepSeekHealthCheck {
    
    private static final Logger log = LoggerFactory.getLogger(DeepSeekHealthCheck.class);
    
    @Value("${langchain4j.open-ai.chat-model.api-key:}")
    private String apiKey;
    
    @Value("${langchain4j.open-ai.chat-model.base-url:https://api.deepseek.com}")
    private String baseUrl;
    
    // 健康检查超时时间（秒）
    private static final int HEALTH_CHECK_TIMEOUT = 10;
    
    public Map<String, Object> checkHealth() {
        Map<String, Object> result = new HashMap<>();
        try {
            log.debug("开始DeepSeek健康检查");
            
            // 检查API密钥配置
            if (apiKey == null || apiKey.trim().isEmpty()) {
                result.put("status", "DOWN");
                result.put("error", "DeepSeek API密钥未配置");
                result.put("service", "DeepSeek AI");
                result.put("lastCheck", java.time.LocalDateTime.now().toString());
                return result;
            }
            
            // 测试API连接
            HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(HEALTH_CHECK_TIMEOUT))
                .build();
                
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(baseUrl + "/v1/models"))
                .header("Authorization", "Bearer " + apiKey)
                .timeout(Duration.ofSeconds(HEALTH_CHECK_TIMEOUT))
                .GET()
                .build();
                
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            
            if (response.statusCode() == 200) {
                result.put("status", "UP");
                result.put("service", "DeepSeek AI");
                result.put("message", "DeepSeek AI服务运行正常");
                result.put("baseUrl", baseUrl);
                result.put("lastCheck", java.time.LocalDateTime.now().toString());
                log.debug("DeepSeek健康检查成功");
            } else {
                result.put("status", "DOWN");
                result.put("service", "DeepSeek AI");
                result.put("error", "API响应状态码: " + response.statusCode());
                result.put("lastCheck", java.time.LocalDateTime.now().toString());
            }
            
        } catch (Exception e) {
            log.error("DeepSeek健康检查失败: {}", e.getMessage(), e);
            
            String errorMessage = getErrorMessage(e);
            
            result.put("status", "DOWN");
            result.put("service", "DeepSeek AI");
            result.put("error", errorMessage);
            result.put("exception", e.getClass().getSimpleName());
            result.put("lastCheck", java.time.LocalDateTime.now().toString());
            result.put("message", "DeepSeek AI服务不可用");
        }
        
        return result;
    }
    
    /**
     * 根据异常类型返回友好的错误消息
     */
    private String getErrorMessage(Exception e) {
        String message = e.getMessage();
        
        if (message == null) {
            return "未知错误";
        }
        
        // API密钥相关错误
        if (message.contains("401") || message.contains("Unauthorized") || message.contains("Invalid API key")) {
            return "API密钥无效或已过期";
        }
        
        // 配额相关错误
        if (message.contains("429") || message.contains("quota") || message.contains("rate limit")) {
            return "API调用配额已用完或请求频率过高";
        }
        
        // 网络连接错误
        if (message.contains("Connection") || message.contains("timeout") || message.contains("UnknownHost")) {
            return "网络连接失败";
        }
        
        // 服务器错误
        if (message.contains("500") || message.contains("502") || message.contains("503")) {
            return "DeepSeek服务器内部错误";
        }
        
        // 返回原始错误消息（截取前100个字符）
        return message.length() > 100 ? message.substring(0, 100) + "..." : message;
    }
    
    /**
     * 手动触发健康检查
     * @return 健康检查结果
     */
    public Map<String, Object> performHealthCheck() {
        log.info("手动触发DeepSeek健康检查");
        return checkHealth();
    }
    
    /**
     * 检查API密钥是否配置
     * @return 是否配置了API密钥
     */
    public boolean isApiKeyConfigured() {
        String apiKey = System.getenv("DEEPSEEK_API_KEY");
        return apiKey != null && !apiKey.trim().isEmpty() && apiKey.startsWith("sk-");
    }
    
    /**
     * 获取API密钥状态信息
     * @return API密钥状态
     */
    public String getApiKeyStatus() {
        String apiKey = System.getenv("DEEPSEEK_API_KEY");
        
        if (apiKey == null || apiKey.trim().isEmpty()) {
            return "未配置";
        }
        
        if (apiKey.startsWith("sk-")) {
            return "已配置 (长度: " + apiKey.length() + ")";
        }
        
        return "格式错误";
    }
}